package com.example.zbh.dsliao.ui.activty;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.model.entity.VideoEntity;
import com.example.zbh.dsliao.ui.adapter.VideoAdapter;
import com.example.zbh.dsliao.utils.video.BuildConfig;
import com.example.zbh.dsliao.utils.video.ImageCache;
import com.example.zbh.dsliao.utils.video.ImageResizer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zbh on 15/11/28.
 */
public class SendVideoActivity extends BaseFragmentActivity implements AdapterView.OnItemClickListener {
    private int size;
    private int space;
    private ImageResizer imageResizer;
    private List<VideoEntity> list;
    private GridView gridView;
    private VideoAdapter videoAdapter;
    @Override
    protected int getLayOut() {
        return R.layout.activity_send_video;
    }

    @Override
    protected void initView() {
        gridView = findeView(R.id.gridView);



    }

    @Override
    protected void initData() {
        size = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
        space = getResources().getDimensionPixelOffset(R.dimen.image_thumbnail_spacing);
        list = new ArrayList<>();
        getVideoFile();
        videoAdapter = new VideoAdapter();
        ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams();
        cacheParams.setMemCacheSizePercent(0.25f);
        imageResizer = new ImageResizer(this, size);
        imageResizer.setLoadingImage(R.mipmap.dl_empty_photo);
        imageResizer.addImageCache(getSupportFragmentManager(), cacheParams);
        gridView.setAdapter(videoAdapter);
        videoAdapter.addData(list, imageResizer);
        gridView.setOnItemClickListener(this);
        gridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
                    imageResizer.setPauseWork(true);
                }else {
                    imageResizer.setPauseWork(false);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        gridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int numColumns = (int) Math.floor(gridView.getWidth() / (space +size));
                if (numColumns > 0){
                    int columnWidth = (gridView.getWidth() / numColumns) - space;
                    videoAdapter.setItemHeight(columnWidth);
                    if (BuildConfig.DEBUG){
                        Log.i("nannannan", "initData - numColumns set to" + numColumns);
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
                        gridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }else {
                        gridView.getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                    }
                }

            }
        });

    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    imageResizer.setPauseWork(true);
        if (position == 0){
            Intent intent = new Intent();
            intent.setClass(this, RecorderVideoActivity.class);
            startActivityForResult(intent, 100);
        }else {
            VideoEntity videoEntity = list.get(position);
            if (videoEntity.size > 1024 * 1024 * 10){
                Toast.makeText(this,"视频不能超过10M", Toast.LENGTH_SHORT ).show();
                return;
            }else {
                Intent intent = getIntent();
                intent.putExtra("path", videoEntity.filePath);
                intent.putExtra("dur", videoEntity.duration);
                setResult(RESULT_OK, intent);
                finish();

            }

        }


    }

    private void getVideoFile() {
        ContentResolver contentResolver = this.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Video.DEFAULT_SORT_ORDER);
        if (cursor != null && cursor.moveToFirst()){
            do {
                // ID:MediaStore.Audio.Media._ID
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
                // 名称：MediaStore.Audio.Media.TITLE
                String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
                // 路径：MediaStore.Audio.Media.DATA
                String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                // 总播放时长：MediaStore.Audio.Media.DURATION
                int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
                // 大小：MediaStore.Audio.Media.SIZE
                int l = (int) cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
                VideoEntity video = new VideoEntity();
                video.ID = id;
                video.title = title;
                video.filePath = url;
                video.duration = duration;
                video.size = l;
                list.add(video);
            }while (cursor.moveToNext());
        }
        if (cursor != null){
            cursor.close();
            cursor = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0){
            return;
        }
        if (requestCode == 100){
            Uri uri = data.getParcelableExtra("uri");
            String[] projects = new String[]{MediaStore.Video.Media.DATA, MediaStore.Video.Media.DURATION};
            Cursor cursor = this.getContentResolver().query(uri,projects,null,null,null);
            int duration = 0;
            String filePath = null;
            if (cursor.moveToFirst()){
                filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
            }
            if (cursor != null){
                cursor.close();
                cursor = null;
            }
            setResult(RESULT_OK,getIntent().putExtra("path", filePath).putExtra("dur", duration));
            finish();

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        imageResizer.closeCache();
        imageResizer.clearCache();
    }
}
